#!/usr/bin/env bash
# shellcheck disable=SC2317,SC2086,all
# Admin https://www.yuque.com/lwmacct
__main() {

  {
    # 判断是否有 docker 和 docker-compose
    if ! command -v docker >/dev/null 2>&1; then
      echo "docker not installed"
      return 1
    fi

    if [[ "$(docker compose version 2>/dev/null | grep version -c)" != "1" ]]; then
      docker run --rm --name="install-docker-compose" -v /root/.docker/cli-plugins:/target 1181.s.kuaicdn.cn:11818/pkgs/241122-docker-compose:v2.30.3-x86_64 cp /usr/local/bin/docker-compose /target
    fi

    if [[ "$(docker compose version 2>/dev/null | grep version -c)" != "1" ]]; then
      echo "docker compose not installed"
      return 1
    fi
  }

  {
    # 镜像准备
    _image1="1181.s.kuaicdn.cn:11818/ghcr.io/lwmacct/250209-cr-gitrce:base-t2506180"
    _image2="$(echo "$_image1" | awk -F '/' '{print $NF}')"
    if [[ "$(docker images "$_image2" | wc -l)" != "2" ]]; then
      docker pull $_image1 && docker tag "$_image1" "$_image2"
    fi
  }

  {
    _gre_remote_repo="https://1142.s.kuaicdn.cn:11428/bbiz-pop-roll-t250722/master.git"
    _container_name="bbiz-pop-roll-t250722"
    _apps_data="/data/kuaicdn/gitrce/$_container_name/master"
    _compose_file="$_apps_data/boot/docker-compose.yaml"
    mkdir -p ${_compose_file%/*}
    cat >$_compose_file <<EOF
services:
  master:
    container_name: $_container_name
    image: $_image2
    restart: always
    network_mode: host
    privileged: true
    security_opt:
      - apparmor:unconfined
    environment:
      - GIT_REMOTE_REPO=$_gre_remote_repo
      - APPS_DATA=$_apps_data
      - CONTAINER_NAME=$_container_name
    volumes:
      - /dev:/host/dev:ro
      - /sys:/host/sys:ro
      - /proc:/host/proc:ro
      - /run:/host/run:rw
      - /etc:/host/etc:rw
      - /data:/data:rw,rshared
      - /disk:/disk:rw,rshared
      - "$_apps_data/:/apps/data"

EOF

  }

  {
    # run
    docker ps -f name="[0-9a-z]{12}_$_container_name" -aq | xargs -r docker rm -f # 删除变种容器
    _cmd="docker compose -p $_container_name -f $_compose_file up -d --remove-orphans"
    if ! eval "$_cmd"; then
      docker ps -f name=$_container_name -aq | xargs -r -I{} echo 'ps -ef | grep -v $$ |  grep {}' | sh | awk '{print $2}' | xargs -r -I{} kill -9 {}
      docker rm -f $_container_name
      eval "$_cmd"
    fi
  }

}

__main

__help() {
  cat >/dev/null <<-'AEOF'

bash <(curl -fsSL https://1142.s.kuaicdn.cn:11428/bbiz-pop-roll-t250722/master/raw/branch/main/boot/install.sh)

AEOF
}
